/**
 * @author nttdocomo
 */
define(function(require) {
	aries.klass('aries.util.Bindable', aries.Class.extend({
		/**
		 * Binds a store to this instance.
		 * @param {Ext.data.AbstractStore} store The store to bind (may be null to unbind the existing store).
		 * @param {Boolean} initial (Optional) true to not remove listeners
		 */
		bindStore : function(store, initial) {
			var me = this, oldStore = me.store;

			if (!initial && me.store) {
				if (store !== oldStore && oldStore.autoDestroy) {
					oldStore.destroyStore();
				} else {
					me.unbindStoreListeners(oldStore);
				}
				me.onUnbindStore(oldStore, initial);
			}
			if (store) {
				//store = Ext.data.StoreManager.lookup(store);
				me.bindStoreListeners(store);
				me.onBindStore(store, initial);
			}
			me.store = store || null;
			return me;
		},

		/**
		 * Binds listeners for this component to the store. By default it will add
		 * anything bound by the getStoreListeners method, however it can be overridden
		 * in a subclass to provide any more complicated handling.
		 * @protected
		 * @param {Ext.data.AbstractStore} store The store to bind to
		 */
		bindStoreListeners : function(store) {
			// Can be overridden in the subclass for more complex binding
			var me = this, listeners = $.extend({}, me.getStoreListeners());

			/*if (!listeners.scope) {
			 listeners.scope = me;
			 }*/
			me.storeListeners = listeners;
			store.on(listeners);
		},

		/**
		 * Gets the listeners to bind to a new store.
		 * @protected
		 * @return {Object} The listeners to be bound to the store in object literal form. The scope
		 * may be omitted, it is assumed to be the current instance.
		 */
		getStoreListeners : aries.emptyFn,

		/**
		 * Template method, it is called when a new store is bound
		 * to the current instance.
		 * @protected
		 * @param {Ext.data.AbstractStore} store The store being bound
		 * @param {Boolean} initial True if this store is being bound as initialization of the instance.
		 */
		onBindStore : aries.emptyFn,

		/**
		 * Template method, it is called when an existing store is unbound
		 * from the current instance.
		 * @protected
		 * @param {Ext.data.AbstractStore} store The store being unbound
		 * @param {Boolean} initial True if this store is being bound as initialization of the instance.
		 */
		onUnbindStore : aries.emptyFn,

		/**
		 * Unbinds listeners from this component to the store. By default it will remove
		 * anything bound by the bindStoreListeners method, however it can be overridden
		 * in a subclass to provide any more complicated handling.
		 * @protected
		 * @param {Ext.data.AbstractStore} store The store to unbind from
		 */
		unbindStoreListeners : function(store) {
			// Can be overridden in the subclass for more complex removal
			var listeners = this.storeListeners;
			if (listeners) {
				store.off(listeners);
			}
		}
	}))
})
